<?php
/**
 * https://gitee.com/Mao02
 * http://www.dazhetu.cn/
 * jay_fun 410136330@qq.com
 * Date: 2019/4/16
 * Time: 17:56
 */

class SearchController extends Controller_Base
{
    public function indexAction()
    {
        $request = $this->getRequest();
        $keyword = $request->getQuery('keyword');
        $page = $request->getQuery('p',1);
        $per_page = 10;
        $offset = $per_page*($page-1);
        try{
            $xs = new XS(APPLICATION_PATH.'/application/library/Xunsearch/article.ini');
            $docs = $xs->search->setQuery($keyword." AND state:1")
                ->setLimit($per_page,$offset)
                ->setFuzzy(true)
                ->search(); // 执行搜索，将搜索结果文档保存在 $docs 数组中
            $list = [];
            foreach ($docs as $doc)
            {
                $list[] = [
                    'id' => $doc->id,
                    'title' => $xs->search->highlight($doc->title),
                    'content' => $xs->search->highlight($doc->content),
                    'create_time' => $doc->create_time,
                    'state' => $doc->state,
                ];
            }
        }catch (\XSException $e){
            die($e->getMessage());
        }
        // 分页
        $count = $xs->search->getLastCount();
        if ($count > $per_page) {
            $pb = max($page - 5, 1);
            $pe = min($pb + 10, ceil($count / $per_page) + 1);
            $pager = '<nav aria-label="Page navigation"><ul class="pagination">';
            do {
                if ($pb == $page){
                    $pager .= '<li class="disabled page-item"><span class="page-link">' . $page . '</span></li>';
                }else{
                    $pager .= '<li class="page-item"><a class="page-link" href="' . url('blog/search/index').'?keyword='. $keyword . '&p=' . $pb  . '">' . $pb . '</a></li>';
                }
            } while (++$pb < $pe);
            $pager .= '</ul></nav>';
            $this->getView()->assign('pager',$pager);
        }

        $this->assignSeo();

        $this->getView()->assign('keyword',$keyword);
        $this->getView()->assign('list',$list);
        return $this->getView()->display('search/index.phtml');
    }
}